package com.itheima.health.controller.mobile;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.utils.AliyunSmsTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mobile")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AliyunSmsTemplate aliyunSmsTemplate;

    @Autowired
    private MemberService memberService;

    @PostMapping("/login/smsLogin")
    public Result smsLogin(@RequestBody Map map) {
        String telephone = map.get("telephone").toString();
        String code=redisTemplate.opsForValue().get(telephone+"MOBILE_SIGNIN").toString();
        String validateCode=map.get("validateCode").toString();
        if (code.equals(validateCode)){
            Member member=memberService.getByPhoneNumber(telephone);
            if (member==null){
                Member newMember=new Member();
                newMember.setPhoneNumber(telephone);
                newMember.setRegTime(new Date());
                memberService.create(newMember);
            }
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        return new Result(false,MessageConst.LOGIN_FAIL);
    }

    @PostMapping("/validateCode/send")
    public Result validateCode(@RequestParam String telephone, @RequestParam String type) {
//        String code=aliyunSmsTemplate.sendSms(telephone);
        String code="1234";
        redisTemplate.opsForValue().set(telephone+type,code);
        redisTemplate.expire(telephone+type,1, TimeUnit.MINUTES);
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }
}
